"""
应用配置管理
"""

from pydantic_settings import BaseSettings
from typing import List, Optional, Union
import os
from pydantic import Field, validator
from dotenv import load_dotenv

# 手动加载.env文件，确保.env文件优先级高于环境变量
load_dotenv(override=True)


class Settings(BaseSettings):
    """应用配置 - 优先从.env文件读取"""
    
    # 应用基本信息
    APP_NAME: str = Field(default="AI测试助手", env="APP_NAME")
    APP_VERSION: str = Field(default="2.0.0", env="APP_VERSION")
    DEBUG: bool = Field(default=True, env="DEBUG")
    
    # 服务器配置
    HOST: str = Field(default="0.0.0.0", env="HOST")
    PORT: int = Field(default=8000, env="PORT")
    
    # 安全配置
    SECRET_KEY: str = Field(..., env="SECRET_KEY", description="必须设置密钥")
    ALGORITHM: str = Field(default="HS256", env="ALGORITHM")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(default=30 * 24 * 60, env="ACCESS_TOKEN_EXPIRE_MINUTES")
    
    # 数据库配置
    DATABASE_URL: str = Field(..., env="DATABASE_URL", description="必须设置数据库连接")
    
    # CORS配置
    ALLOWED_HOSTS: Union[str, List[str]] = Field(
        default=["http://localhost:3000", "http://127.0.0.1:3000"],
        env="ALLOWED_HOSTS"
    )
    
    # 文件上传配置
    UPLOAD_DIR: str = Field(default="uploads", env="UPLOAD_DIR")
    MAX_FILE_SIZE: int = Field(default=50 * 1024 * 1024, env="MAX_FILE_SIZE")
    ALLOWED_EXTENSIONS: List[str] = Field(
        default=[".pdf", ".docx", ".doc", ".txt", ".md", ".xlsx", ".xls", ".pptx", ".ppt"],
        env="ALLOWED_EXTENSIONS"
    )
    
    # AI配置
    OPENAI_API_KEY: Optional[str] = Field(default=None, env="OPENAI_API_KEY")
    OPENAI_BASE_URL: str = Field(default="https://api.openai.com/v1", env="OPENAI_BASE_URL")
    AI_MODEL: str = Field(default="gpt-3.5-turbo", env="AI_MODEL")
    
    # AI提示词配置
    CUSTOM_SYSTEM_PROMPT: Optional[str] = Field(default=None, env="CUSTOM_SYSTEM_PROMPT")
    CUSTOM_REQUIREMENT_ANALYSIS_PROMPT: Optional[str] = Field(default=None, env="CUSTOM_REQUIREMENT_ANALYSIS_PROMPT")
    CUSTOM_TEST_CASE_GENERATION_PROMPT: Optional[str] = Field(default=None, env="CUSTOM_TEST_CASE_GENERATION_PROMPT")
    CUSTOM_CODE_REVIEW_PROMPT: Optional[str] = Field(default=None, env="CUSTOM_CODE_REVIEW_PROMPT")
    CUSTOM_API_DOCUMENTATION_PROMPT: Optional[str] = Field(default=None, env="CUSTOM_API_DOCUMENTATION_PROMPT")
    
    # 日志配置
    LOG_LEVEL: str = Field(default="INFO", env="LOG_LEVEL")
    LOG_FILE: str = Field(default="logs/app.log", env="LOG_FILE")
    
    @validator('ALLOWED_HOSTS', pre=True)
    def parse_allowed_hosts(cls, v):
        """解析ALLOWED_HOSTS，支持字符串和列表格式"""
        if isinstance(v, str):
            # 如果是字符串，尝试按逗号分割
            if ',' in v:
                return [host.strip() for host in v.split(',')]
            else:
                return [v.strip()]
        elif isinstance(v, list):
            return v
        else:
            return ["http://localhost:3000", "http://127.0.0.1:3000"]
    
    @validator('ALLOWED_EXTENSIONS', pre=True)
    def parse_allowed_extensions(cls, v):
        """解析ALLOWED_EXTENSIONS，支持字符串和列表格式"""
        if isinstance(v, str):
            # 如果是字符串，尝试按逗号分割
            if ',' in v:
                return [ext.strip() for ext in v.split(',')]
            else:
                return [v.strip()]
        elif isinstance(v, list):
            return v
        else:
            return [".pdf", ".docx", ".doc", ".txt", ".md", ".xlsx", ".xls", ".pptx", ".ppt"]
    
    class Config:
        env_file = ".env"
        case_sensitive = True
        env_file_encoding = 'utf-8'
        # .env文件优先级高于环境变量
        env_nested_delimiter = '__'


# 创建配置实例
settings = Settings()

# 确保必要的目录存在
os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
os.makedirs(os.path.dirname(settings.LOG_FILE), exist_ok=True) 